package controller;

import java.io.StringReader;
import java.rmi.RemoteException;
import java.util.ArrayList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;

import data.Player;

public class ServicePlayerImpl implements ServicePlayer,Runnable{
	//web service
	private WebResource servicePlayer;
	
	//storing the connected players
	private ArrayList<Player> connectedPlayers;
	
	public ServicePlayerImpl(){
		connectedPlayers=new ArrayList<Player>();
	}
	
	public void run() {
		servicePlayer= Client.create().resource("http://localhost:8080/bataille");
		while(true)	{
			try {
				Thread.sleep(3000) ;
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}
	}
	public boolean abonner(Player p) throws RemoteException {
		connectedPlayers.add(p);
		return false;
	}

	public void desabonner(Player p) throws RemoteException {
		connectedPlayers.remove(p);
	}

	public Player connexion(String login) throws RemoteException {		
		System.out.println("dzedzeoidzed");
		Player player;
		String response=servicePlayer.path("/player/"+login).get(String.class);
		JAXBContext context;
		try{
			context = JAXBContext.newInstance(Player.class);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			StringBuffer xmlStr = new StringBuffer(response);
			JAXBElement<Player> root = unmarshaller.unmarshal(new StreamSource(new StringReader(xmlStr.toString())),Player.class);
			player= root.getValue();
			if (player.getId()==null){
				response=servicePlayer.path("/player/add/"+login).get(String.class);
				unmarshaller=context.createUnmarshaller();
				xmlStr = new StringBuffer(response);
				root = unmarshaller.unmarshal(new StreamSource(new StringReader(xmlStr.toString())),Player.class);
				player= root.getValue();
				System.out.println("Il n'existe pas --> Joueur ajouté");
			}
			System.out.println("Abonnement du joueur "+ player.getLogin() +" au service");
			this.abonner(player);
			return player;
		} catch (JAXBException e){
			System.out.println("bla");
			e.printStackTrace();
			return null;
		}
	}
	public boolean deconnexion(Player p) throws RemoteException{
		this.desabonner(p);
		return false;
	}

}
